<?php
/**
 * Descript:
 * User: lufeng501206@gmail.com
 * Date: 2017/3/7 22:08
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Models\Home\User;
use App\Models\LoginLogs;
use App\Repositories\AliRepos;
use App\Repositories\TasksRepos;
use App\Repositories\UsersRepos;
use Illuminate\Http\Request;

class IndexController extends Controller
{
    private $tasksRepos;
    private $aliRepos;
    private $usersRepos;

    public function __construct(AliRepos $aliRepos, TasksRepos $tasksRepos, UsersRepos $usersRepos)
    {
        $this->middleware('verify.wechat', ['except' => ['sendVerifyCode', 'bindMobile']]);
        $this->tasksRepos = $tasksRepos;
        $this->aliRepos = $aliRepos;
        $this->usersRepos = $usersRepos;
    }

    public function index()
    {
        header('location:web');
    }

    /**
     * 用户登录
     * @param Request $request
     */
    public function login(Request $request)
    {
        $inputs = $request->input();
        $mobie = $inputs['mobile'];
        $password = $inputs['password'];
        $userModel = User::where('account', $mobie)->first();
        if (!empty($userModel)) {
            if (password_verify($password, $userModel->password)) {
                $request->session()->put('login_user', $inputs['mobile']);
                $this->writeLoginLog($inputs['mobile'], $request);
                return successJson([], '登录成功');
            } else {
                return errorJson([], '密码错误');
            }
        } else {
            return errorJson([], '用户不存在');
        }
    }

    /**
     * 快速登录
     * @param Request $request
     */
    public function quickLogin(Request $request)
    {
        $inputs = $request->input();
        $mobile = $inputs['mobile'];
        $verifyCode = $request->session()->get('verify_code');
        $verifyTime = $request->session()->get('code_time');
        $userModel = User::where('mobile', $mobile)->first();
        if (empty($verifyCode) || (time() - $verifyTime > 600)) {
            return errorJson([], '验证码已过期');
        }
        if (!empty($userModel)) {
            if ($verifyCode == $inputs['verify_code']) {
                $request->session()->put('login_user', $inputs['mobile']);
                $this->writeLoginLog($inputs['mobile'], $request);
                return successJson([], '登录成功');
            } else {
                return errorJson([], '验证码错误');
            }
        } else {
            return errorJson([], '用户不存在');
        }
    }

    /**
     * 注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function register(Request $request)
    {
        $inputs = $request->input();
        //验证手机号码
        $verifyCode = $request->session()->get('verify_code');
        $verifyTime = $request->session()->get('code_time');
        if (empty($verifyCode) || (time() - $verifyTime > 600)) {
            return errorJson([], '验证码已过期');
        }
        if ($verifyCode != $inputs['verify_code']) {
            return errorJson([], '验证码错误');
        }
        // 判断是否已经注册过
        $userModel = User::where('account', $inputs['mobile'])->first();
        if (!empty($userModel)) {
            return errorJson([], '该手机号码已经被注册过');
        }
        $userModel = new User();
        $userModel->account = $inputs['mobile'];
        $userModel->mobile = $inputs['mobile'];
        $userModel->user_type = 2;
        if (!empty($inputs['recommend_user']) && $inputs['recommend_user'] != $inputs['mobile']) {
            $userModel->recommend_user = $inputs['recommend_user'];
        }
        $res = $userModel->save();
        if ($res) {
            //保存session
            $request->session()->put('login_user', $inputs['mobile']);
            $this->writeLoginLog($inputs['mobile'], $request);
            return successJson([], '注册成功');
        } else {
            return errorJson([], '注册失败');
        }
    }

    /**
     * 发送验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function sendVerifyCode(Request $request)
    {
        $inputs = $request->input();
        $mobile = $inputs['mobile'];
        $verifyCode = $this->aliRepos->sendCode($mobile);
        if (!empty($verifyCode)) {
            $request->session()->put('verify_code', $verifyCode);
            //配置验证码存储时间
            $request->session()->put('code_time', time());
            return successJson([], '发送成功');
        } else {
            return errorJson([], '发送失败');
        }
    }

    /**
     * 绑定手机
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function bindMobile(Request $request)
    {
        $inputs = $request->input();
        $mobile = $inputs['mobile'];
        $verifyCode = $request->session()->get('verify_code');
        $verifyTime = $request->session()->get('code_time');
        if (empty($verifyCode) || (time() - $verifyTime > 600)) {
            return errorJson([], '验证码已过期');
        }
        if ($verifyCode != $inputs['verify_code']) {
            return errorJson([], '验证码错误');
        }
        $userId = $this->usersRepos->getLoginUserId();
        $userModel = User::FindOrFail($userId);
        if ($userModel->user_type == 1) {
            $userModel->mobile = $mobile;
        } else {
            $userModel->account = $mobile;
            $userModel->mobile = $mobile;
        }
        $res = $userModel->save();
        if ($res) {
            return successJson('', '手机绑定成功');
        } else {
            return errorJson('', '手机绑定失败');
        }
    }


    /**
     * 写入登录日志
     */
    private function writeLoginLog($mobile, $request)
    {
        $loginLogModel = new LoginLogs();
        $loginLogModel->client_ip = $request->getClientIp();
        $loginLogModel->mobile = $mobile;
        $loginLogModel->save();
        return true;
    }
}